package com.mhkj.common.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.mhkj.base.rbac.user.controller.LoginController;
import com.mics.core.common.constant.Constants;

/**
 * 登陆拦截
 * @author mics
 * @date 2018年6月28日
 * @version 1.0
 */
@Component 
public class LoginInterceptor implements HandlerInterceptor{
	@Autowired
	LoginController controller;


    private static final String[] IGNORE_URI = { "/workFlowLogger","/workflow","/newInfo","/info",
    		"/professionalPlanNode/listByPage","/planTempData/listByPage","/planNodeAdjust",
    		"/monthlyPlanExecution","/fileCommon/loadFileList"};
    /**   
     * 进入controller层之前拦截请求   
     * @param httpServletRequest   
     * @param httpServletResponse   
     * @param o   
     * @return   
     * @throws Exception   
     */    
    public  @Override boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {   
    	 HttpSession session = httpServletRequest.getSession();
         String url = httpServletRequest.getRequestURL().toString();
         for (String s : IGNORE_URI) {
             if (url.contains(s)) {
             	return true;
             }
         }
    	 Cookie[] cookies = httpServletRequest.getCookies();
         String sessionId="";
         if(cookies != null){  
             for (Cookie cookie : cookies) {
             	if(cookie.getName().equals("SESSION")) {
             		sessionId=cookie.getValue();
             	}
             }  
         }
         
         if(session.isNew()) {//验证是否登录
	         if(sessionId!=null) {
	        	 controller.isLogin(sessionId,httpServletRequest,httpServletResponse);
	         }
         }
         if(!StringUtils.isEmpty(session.getAttribute(Constants.CURRENT_USER))){    
             return true;    
         }else{    
             httpServletResponse.sendRedirect("/login.html"); 
         	return false;    
         }    
    }    
}
